import React, { useEffect, useState } from "react";
import { Swiper, Image, Dialog, Popup, PopupPosition, Toast } from "react-vant";
import { Button } from "react-vant";
import { useNavigate } from "react-router-dom";
import axios from "../../utils/request";
import Calendars from "../../components/Calendars";
import Luo from "iscroll-luo";
type Props = {};

const Home = (props: Props) => {
  const navigate = useNavigate();
  const [travel, setTravel]: any = useState([]);
  //获取出行快讯数据
  useEffect(() => {
    (async () => {
      let res = await axios("/travel");
      setTravel(res.data);
    })();
  }, []);

  //起始站
  const [start, setStart] = useState(localStorage.getItem("start") || "北京");
  //跳转到起始站页面
  const goStart = () => {
    navigate("/start");
  };
  //终点站
  const [end, setEnd] = useState(localStorage.getItem("end") || "上海");
  //跳转到终点站页面
  const goEnd = () => {
    navigate("/end");
  };
  //反转站点
  const reversal = () => {
    setStart(end);
    setEnd(start);
  };
  //本地存储反转后的站点
  localStorage.setItem("start", start);
  localStorage.setItem("end", end);
  //监听起始站和终点站
  useEffect(() => {
    if (start === end) {
      setEnd("请选择");
    }
  }, [start, end]);
  //获取当前日期
  const mou = new Date().getMonth() + 1;
  const day = new Date().getDate();
  const tiems: any = localStorage.getItem("date") || mou + "月" + day + "日";
  const [time, setTime] = useState(`${mou}月${day}日`);
  useEffect(() => {
    localStorage.setItem("date", time);
  }, []);
  useEffect(() => {
    setTime(tiems);
  }, [tiems]);
  //日历弹框
  const [state, setState] = useState<PopupPosition>("");
  const [showCloseIcon, setShowCloseIcon] = useState(false);
  //首页轮播图懒加载
  const [imgUrl, setImgUrl] = useState([
    { img: require("../../img/home/swiper.jpg") },
    { img: require("../../img/home/swiper.jpg") },
    { img: require("../../img/home/swiper.jpg") },
  ]);
  //获取是否存储token
  const token = localStorage.getItem("token") || "";
  //历史数据的数组
  const [historyList, setHistoryList] = useState(
    JSON.parse(localStorage.getItem("historyList") as string) || []
  );
  //查询按钮
  const query = async () => {
    if (token) {
      //历史数据的处理
      let obj = {
        start,
        end,
      };
      if (historyList.length < 3) {
        await setHistoryList([...historyList, obj]);
      } else {
        await setHistoryList(historyList.splice(0, 1));
        await setHistoryList([...historyList, obj]);
      }

      navigate("/querylist");
    } else {
      Dialog.confirm({
        message: "当前未登录是否跳转登录页面",
      })
        .then(() => {
          navigate("/login");
        })
        .catch(() => {
          console.log("catch");
        });
    }
  };
  //清除历史数据
  const delHistoryList = () => {
    setHistoryList([]);
  };
  //历史数据存储
  localStorage.setItem("historyList", JSON.stringify(historyList));
  //上拉下拉
  const onDown = () => {
    setTimeout(() => {
      Toast("刷新成功");
      (async () => {
        let res = await axios("/travel");
        setTravel(res.data);
      })();
    }, 1000);
  };
  const onUp = () => {
    setTimeout(() => {
      Toast("加载成功");
      (async () => {
        let res = await axios("/travel");
        setTravel([...travel, ...res.data]);
      })();
    }, 1000);
  };
  return (
    <div className="home">
      <div className="index_box">
        <div className="top">
          <div>
            <span onClick={goStart}>{start}</span>
            <img
              src={require("../../img/home/箭头_左右切换_o .png")}
              onClick={reversal}
            />
            <span onClick={goEnd}>{end}</span>
          </div>
          <div>
            <span onClick={() => setShowCloseIcon(true)}>{time}</span>
          </div>
        </div>
        <div className="bottom">
          <Button onClick={query} round size="large" color="#FF8D41">
            查询
          </Button>
          <div>
            <div>
              {historyList.length > 0 ? (
                historyList.map((item: any, index: string) => {
                  return (
                    <span key={index}>
                      {item.start}-{item.end}
                    </span>
                  );
                })
              ) : (
                <span>暂无数据</span>
              )}
            </div>
            <span onClick={delHistoryList} style={{ color: "#000" }}>
              清除历史
            </span>
          </div>
        </div>
      </div>
      <header>
        <div className="box1">
          <div>
            <div className="kong"></div>
            <span>火车票预订</span>
            <p>便捷购票,服务您的每一次出行</p>
          </div>
        </div>
      </header>
      <main>
        <div className="kong"></div>
        <div className="swiper demo-swiper">
          <Swiper>
            {imgUrl.map((item, index) => (
              <Swiper.Item key={index}>
                <Image lazyload src={item.img} />
              </Swiper.Item>
            ))}
          </Swiper>
        </div>
        <div className="Travel">
          <div className="header">
            <h4>出行快讯</h4>
            <span>更多{">"}</span>
          </div>
          <div style={{ position: "relative", height: "55vh" }}>
            <Luo id="id" onDown={onDown} onUp={onUp}>
              {travel &&
                travel.map((item: any, index: any) => {
                  return (
                    <div className="box" key={index}>
                      <div className="zuo">{item.id}</div>
                      <div className="zhong">
                        <div>{item.title}</div>
                        <div className="zhong_box">
                          <span>{item.text}</span>
                          &emsp;
                          <span>{item.date}</span>
                        </div>
                      </div>
                      <div className="you">
                        {/* 懒加载 */}
                        <Image width={80} height={80} lazyload src={item.img} />
                      </div>
                    </div>
                  );
                })}
            </Luo>
          </div>

          <div
            style={{
              background: "rgb(245, 245, 245)",
              width: "100%",
              height: "80px",
            }}
          ></div>
        </div>
      </main>
      <Popup
        visible={showCloseIcon}
        closeable
        style={{ height: "65%" }}
        position="bottom"
        onClose={() => setShowCloseIcon(false)}
      >
        <Calendars setShowCloseIcon={setShowCloseIcon} />
      </Popup>
    </div>
  );
};

export default Home;
